import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import utils.HttpUtils;


public class FollowThatPage {
	
	private static IndexRepository repositorio;

	public static void main (String[] args) throws Exception {
		
		boolean mudou = false;
		
		if (repositorio == null) {
			//carrega index do arquivo
			
			le();
			
			//se nulo cria um
		}
		
//		String content = new Trt22().getConteudoProcesso("0001495");
//		String url = "cautelar";
		
//		String content = new JurisConsult().getConteudoProcesso("4582013");
//		String url = "jurisconsult 4582013";
		
		String content = new GenericUrl().getConteudo("http://www.coroataonlinema.com/");
		String url = "coroata";
		
		int hashCodeAtual = content.hashCode();
		
		Index index = repositorio.search(url);
		
		if (index!=null) {
			if (index.getHashCodeSalvo()!=hashCodeAtual) {
				repositorio.update(url,hashCodeAtual);
				mudou = true;
				avisaMudanca(url);
			}
			else {
				semMudanca(url);
			}	
		}
		else {
			repositorio.insert(url, hashCodeAtual);
			novo(url);
			mudou = true;
		}
		
		if (mudou) {
			//atualiza index repo no arquivo
			atualiza();
		}
	}
	
	

	private static void novo(String url) {
		System.out.println(url + " adicionada");
	}



	private static void semMudanca(String url) {
		System.out.println(url + " nao mudou");
		
	}



	private static void le() {
		
		try {
			
			FileInputStream saveFile = new FileInputStream("test.save");

			ObjectInputStream save = new ObjectInputStream(saveFile);
			
			repositorio = (IndexRepository) save.readObject();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			repositorio = new IndexRepository();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	private static void atualiza() throws IOException {
		
		FileOutputStream saveFile=new FileOutputStream("test.save");
		
		ObjectOutputStream save = new ObjectOutputStream(saveFile);
		
		save.writeObject(repositorio);
		
		save.close();
		
	}

	private static void avisaMudanca(String url) {
		System.out.println(url + " mudou");
		
	}

}
